package loginlog

import (
	"strings"

	"gitee.com/tomatomeatman/golang-repository/bricks3/function/data/iputil"
	"gitee.com/tomatomeatman/golang-repository/bricks3/model/globalvariable"
	"gitee.com/tomatomeatman/golang-repository/bricks3/utils/ginutil"
	"gitee.com/tomatomeatman/golang-repository/bricks3/utils/sqlfactory"
	Log "github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
)

/**
 * 初始化
 */
func init() {
	service := LoginLogService{}
	globalvariable.Add("Module@LoginLogService", &service)
	ginutil.RegisterAfter("/login/in", service.AopAddLog) //当触发"LoginController.In"函数时调用LoginLogService{}.AopAddLog
}

/**
 * 登录日志LoginLog表基本业务操作结构体
 */
type LoginLogService struct {
}

/**
 * 验证更新数据是否存在重复 (一旦使用则覆盖通用方法)
 * @param r Http请求对象
 * @param ip 登录者IP
 * @param nameOrNo 登录者使用的用户名或工号
 * @return *msgentity.MsgEntity 返回验证结果
 */
func (service LoginLogService) AddLog(ctx *gin.Context, sUserId, nameOrNo string) (bool, string, interface{}) {
	ip := iputil.RemoteIp(ctx.Request)
	macAddress := "" //MacAddress.getMac(ip);
	var build strings.Builder
	build.WriteString("INSERT INTO LoginLog (")
	build.WriteString("sName,iType,sUserId,sUser,sIp,sMACAddress,dLogDate,dLastCall")
	build.WriteString(") ")
	build.WriteString(" SELECT")
	build.WriteString(" '登录日志' as sName,")
	build.WriteString(" 1 as iType,")
	build.WriteString(" ? as sUserId,")
	build.WriteString(" ? as sUser,")
	build.WriteString(" ? as sIp,")
	build.WriteString(" ? as sMACAddress,")
	build.WriteString(" NOW() as dLogDate,")
	build.WriteString(" NOW() as dLastCall")

	txt := build.String()
	info := GetBusinessInfo()

	bl, msg, res := sqlfactory.ExecSql(info.DbName, txt, sUserId, nameOrNo, ip, macAddress)
	if !bl {
		return bl, msg, res
	}

	if res.(int64) < 1 {
		Log.Error("新增失败,影响值小于1")
		return false, "新增失败", 1002
	}

	return true, "新增成功", 8999
}

/**
 * Aop方式添加日志
 * @param dateSt 开始时间范围
 * @param dateEd 结束时间范围
 * @return
 */
func (service LoginLogService) AopAddLog(ctx *gin.Context, params ...interface{}) (bool, string, interface{}) {
	if len(params) < 1 {
		return true, "参数错误,但不拦截", 1000
	}

	bl := params[0].(bool)
	if !bl {
		return true, "上层函数未正确执行结束所以不进行记录,但不拦截", 1001
	}

	nameOrNo := ginutil.GetParam(ctx, "nameOrNo", "").(string)
	if nameOrNo == "" {
		return true, "用户名称为空", 8001 //虽然不添加,但不能影响切面
	}

	sUserId := ginutil.GetParam(ctx, "sUserId", "").(string)

	return service.AddLog(ctx, sUserId, nameOrNo)
}
